package com.security.filter.api;

import com.security.filter.domain.SecurityDO;
import com.security.filter.service.SecurityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import java.security.Principal;

/**
 * @Classname SecurityApi
 * @Description TODO
 * @Date 2020/4/21 0021 12:17
 * @Created by 埔枘
 */
@Controller
public class SecurityApi {

    @Autowired
    private SecurityService securityService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @GetMapping(value = "user")
    public String index(@AuthenticationPrincipal Principal principal, Model model){
        model.addAttribute("username",principal.getName());
        return "user";
    }

    @GetMapping(value = "login")
    public String login(){
        return "login";
    }

    @ResponseBody
    @PostMapping(value = "saveUser")
    public SecurityDO saveUser(@RequestBody SecurityDO securityDO){
        securityDO.setPassword(passwordEncoder.encode(securityDO.getPassword()));
        SecurityDO saveUser = securityService.saveUser(securityDO);
        return saveUser;
    }
}
